
package cn.org.seventh.web.common;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @author <a href="mailto:ji.li@symbio-group.com">Andy</a>
 * @since Dec 20, 2007 4:00:27 PM
 */
public abstract class MailService {

    protected static final Log log = LogFactory.getLog(MailService.class);

    private FreeMarkerConfigurer mailTemplateEngine = null;

    public void setMailTemplateEngine(FreeMarkerConfigurer mailTemplateEngine) {
        this.mailTemplateEngine = mailTemplateEngine;
    }

    public abstract void send(SimpleMailMessage msg);

    public void send(String from, String to, String subject, String text) {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(from);
        msg.setTo(to);
        msg.setSubject(subject);
        msg.setText(text);
        send(msg);
    }

    public abstract void send(SimpleMailMessage msg, String templateName,
                              Map model);

    public String generateEmailContent(String templateName, Map map) {
        try {
            Template t =
                mailTemplateEngine.getConfiguration().getTemplate(templateName);
            return FreeMarkerTemplateUtils.processTemplateIntoString(t, map);
        } catch (TemplateException e) {
            log.error("Error while processing FreeMarker template ", e);
        } catch (FileNotFoundException e) {
            log.error("Error while open template file ", e);
        } catch (IOException e) {
            log.error("Error while generate Email Content ", e);
        }
        return null;
    }
}
